package com.mrd.gtimp.business.action;

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.mrd.gtimpframe.entity.CustomCompanyInfo;
import com.mrd.gtimpframe.service.CusInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.mrd.constant.MsgConstants;
import com.mrd.exception.DeleteException;
import com.mrd.exception.SaveException;
import com.mrd.exception.validation.MRDValidationException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.action.DropdownAction;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.business.BusinessModelDto;
import com.mrd.gtimp.business.entity.BaseBusinessModel;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.entity.DeclarationModel;
import com.mrd.gtimp.business.entity.Trail;
import com.mrd.gtimp.business.entity.TrailModel;
import com.mrd.gtimp.business.service.BusinessModelBiz;
import com.mrd.gtimp.business.service.DeclarationBiz;
import com.mrd.gtimp.business.service.DeclarationModelBiz;
import com.mrd.gtimp.business.service.DeclarationPortBiz;
import com.mrd.gtimp.business.service.SuiFuDanBiz;
import com.mrd.gtimp.business.service.TrailBiz;
import com.mrd.gtimp.business.service.TrailModelBiz;
import com.mrd.gtimp.fix.ChnToCodeFix;
import com.mrd.gtimp.order.action.OrderAction;
import com.mrd.gtimpframe.service.TGenSupSrvProvideService;
import com.mrd.util.ExcelImportUtils;
import com.mrd.util.FreeMarkerUtils;
import com.mrd.util.GtimpBusinessUtil;
import com.mrd.util.LoginUtil;
import com.mrd.util.MsgExcel;
import com.mrd.util.ReflectUtil;

@Controller
@RequestMapping("/business")
public class BusinessModelAction extends DropdownAction {

  private static final long serialVersionUID = 1022414240181123821L;

  @Resource
  private BusinessModelBiz businessModelBiz;

  @Resource
  private DeclarationModelBiz declarationModelBiz;

  @Resource
  private TrailModelBiz trailModelBiz;

  @Resource
  private DeclarationBiz declarationBiz;

  @Resource
  private TrailBiz trailBiz;
  @Resource
  private OrderAction orderAction;
  @Resource
  private SuiFuDanBiz suiFuDanBiz;
  @Resource
  private ChnToCodeFix chnToCodeFix;
  @Resource
  private DeclarationPortBiz declarationPortBiz;
  @Resource
  private TGenSupSrvProvideService tGenSupSrvProvideService;
  @Resource
  private CusInfoService cusInfoService;

  public static String SIMPLE_ORDER_DECLARE_PAGE = "/pendingEntryOrder";

  private enum PathEnum {
    saveAsModel;

    public String toPath() {
      return "/gtimp/business/model/" + this.name();
    }
  }

  /**
   * 模板列表页面
   */
  @RequestMapping("/model-main")
  public String main() {
    return "/gtimp/business/businessModelList";
  }

  /**
   * 填写模版名称页面
   */
  @RequestMapping("/model-modelNamePage")
  public String modelNamePage(Trail trail, Declaration declare, Model model) {
    model.addAttribute("trail", trail);
    model.addAttribute("declare", declare);
    return "/gtimp/business/modelNamePage";
  }

  /**
   * 删除模板数据
   */
  @RequestMapping("/model-delete")
  @ResponseBody
  public Result delete() {
    Result msg = null;
    String id = HttpUtils.getParam("id");
    String type = HttpUtils.getParam("type");
    if (id != null && !id.equals("")) {
      try {
        if (type != null && type.equalsIgnoreCase("D")) {
          DeclarationModel declarationModel = new DeclarationModel();
          declarationModel.setId(id);
          declarationModelBiz.deleteModelBiz(declarationModel);
          msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
        } else if (type.equalsIgnoreCase("C")) {
          TrailModel trailModel = new TrailModel();
          trailModel.setId(id);
          trailModelBiz.delete(trailModel);
          msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
        } else {
          msg = Result.newFailInstance(MsgConstants.DEL_FAIL);
        }
      } catch (DeleteException e) {
        e.printStackTrace();
        msg = Result.newFailInstance(MsgConstants.DEL_FAIL);
      }
    }
    return msg;
  }

  @RequestMapping("/model-checkIsExistModel")
  @ResponseBody
  public Result checkIsExistModel() {
    Result msg;
    String modelName = HttpUtils.getParam("model_name");
    String type = HttpUtils.getParam("type");
    if (businessModelBiz.isExistModel(modelName, type)) {
      msg = Result.newFailInstance(MsgConstants.IS_EXISTMODELNAME);
    } else {
      msg = Result.newSuccessInstance(MsgConstants.IS_NONEXISTMODELNAME);
    }
    return msg;
  }

  /**
   * 保存模板
   */
  @RequestMapping("/model-save")
  @ResponseBody
  public Result save(Trail trail) {
    Result msg;
    List<BaseBusinessModel> models = null;
    String declareId = HttpUtils.getParam("declare.id");
    String modelName = HttpUtils.getParam("model_name");
    //判断是否为代录单公司
    String comId=LoginUtil.getLoginUser().getCompany().getId();
    String comType=cusInfoService.selectComTypeById(comId);

    if (modelName != null && !modelName.equals("")) {
      String trailId = trail.getId();
      String isCover = HttpUtils.getParam("isCover");
      String type = "";
      models = new ArrayList<BaseBusinessModel>();
      try {
        BaseBusinessModel model = null;
        if (trailId != null && !trailId.equals("")) {
          type = "C";
          trail = trailBiz.findEntityById(trailId);
          trail.setCommonTemplate("1");
          model = new TrailModel(trail);
          if (!"0".equals(comType)){
            model.setEnter_type("1");
          }else{
            model.setEnter_type("0");
          }
          model.setModel_name(modelName);
          model.setSave_model_time(new Date());
          model.setSave_model_person(LoginUtil.getLoginUser());
          models.add(model);
        }
        if (declareId != null && !declareId.equals("")) {
          type = "D";
          Declaration d = declarationBiz.findEntityById(declareId);
          model = new DeclarationModel(d);
          if (!"0".equals(comType)){
            model.setEnter_type("1");
          }else{
            model.setEnter_type("0");
          }
          model.setModel_name(modelName);
          model.setSave_model_time(new Date());
          model.setSave_model_person(LoginUtil.getLoginUser());
          models.add(model);
        }
        if (isCover != null && isCover.equals("1")) {
          // String hql =
          // "select * from T_BIZ_BASE_BUSINESS_MODEL t where t.model_name='"+modelName+"'
          // and t.type='"+type+"'";
          String hql = "from com.mrd.gtimp.business.entity.BaseBusinessModel where model_name='"
                  + modelName + "' and type='" + type + "'";
          // List<?> deleteModelList = businessModelBiz.findObjectBySql(sql, 0, 0, null);
          List<BaseBusinessModel> deleteModelList =
                  businessModelBiz.findEntityByHql(hql, 0, 0, null);
          for (int i = 0; i < deleteModelList.size(); i++) {
            BaseBusinessModel deleteModel = deleteModelList.get(i);
            if (deleteModel != null) {
              businessModelBiz.delete(deleteModel, true);
            }
          }

        }
        businessModelBiz.saveBusinesses(models);
        msg = Result.newSuccessInstance(MsgConstants.SAVEMODEL_SUCCESS);
      } catch (Exception e) {
        e.printStackTrace();
        msg = Result.newFailInstance(MsgConstants.SAVEMODEL_FAIL);
      }
    } else {
      msg = Result.newFailInstance(MsgConstants.SAVEMODEL_FAIL);
    }
    return msg;
  }

  /**
   * 查询模板列表数据
   */
  @RequestMapping("/model-findList")
  @ResponseBody
  @Json({@JField("id"), @JField("business_id"), @JField("model_name"), @JField("save_model_time"),
          @JField("save_model_person"), @JField("type"), @JField("is_record_info")})
  public Page<BusinessModelDto> findList(Jqgrid jqgrid, String type, String dType,
                                         String isTongguanYth,String isAgent) {
    try {
      // String listCase = "";
      // listCase =
      // " select t_biz_base_business_model.id,t_biz_base_business_model.model_name,"
      // +
      // " to_char( t_biz_base_business_model.save_model_time,'yyyy-mm-dd
      // hh:mi:ss'),t_biz_base_business_model.save_model_person,"
      // +
      // " T_SYS_USER.u_Name,t_biz_base_business_model.type,
      // t_biz_base_business_model.business_id"
      // + " from t_biz_base_business_model t_biz_base_business_model"
      // +
      // " join T_SYS_USER T_SYS_USER on
      // T_SYS_USER.u_Id=t_biz_base_business_model.save_model_person where 1=1 and
      // t_biz_base_business_model.type = '"
      // + type + "'";
      String listCase = "";
      String tgSqlFile = "";
      if (StringUtils.isNotEmpty(isTongguanYth)) {
        tgSqlFile = " and tdm.is_tongguan_yth=" + isTongguanYth;
      }
      if (StringUtils.isNotEmpty(type)) {
        listCase = " select t_biz_base_business_model.id,t_biz_base_business_model.model_name,"
                + " to_char( t_biz_base_business_model.save_model_time,'yyyy-mm-dd hh:mi:ss'),t_biz_base_business_model.save_model_person,"
                + " T_SYS_USER.u_Name,t_biz_base_business_model.type , t_biz_base_business_model.business_id, tdm.is_record_info"
                + " from t_biz_base_business_model t_biz_base_business_model"
                + " join T_SYS_USER T_SYS_USER on T_SYS_USER.u_Id=t_biz_base_business_model.save_model_person "
                + " join t_biz_declaration_model tdm on tdm.id=t_biz_base_business_model.id  where 1=1 and t_biz_base_business_model.type = '"
                + type + "' ";
        listCase = listCase + tgSqlFile;
      } else {
        listCase = " select t_biz_base_business_model.id,t_biz_base_business_model.model_name,"
                + " to_char( t_biz_base_business_model.save_model_time,'yyyy-mm-dd hh:mi:ss'),t_biz_base_business_model.save_model_person,"
                + " T_SYS_USER.u_Name,t_biz_base_business_model.type, t_biz_base_business_model.business_id"
                + " from t_biz_base_business_model t_biz_base_business_model"
                + " join T_SYS_USER T_SYS_USER on T_SYS_USER.u_Id=t_biz_base_business_model.save_model_person where 1=1 ";
      }
      if (StringUtils.isNotEmpty(dType)) {
        listCase += " and tdm.DECLARATION_TYPE = '" + dType + "'";
      } else {
        listCase += " and tdm.DECLARATION_TYPE = 'E'";
      }if(StringUtils.isNotEmpty(isAgent)){
        if ("CROPPED5".equals(isAgent)) {
          listCase += " and t_biz_base_business_model.ENTER_PAGE= 'CROPPED5'";
        }else{
          listCase += " and (t_biz_base_business_model.ENTER_PAGE is null or  t_biz_base_business_model.ENTER_PAGE='COMPLETE5')";
        }
      }

      User user = LoginUtil.getLoginUser();
      String whereCase = "";
      whereCase =
              "and t_biz_base_business_model.customer_com_id = '" + user.getCompany().getId() + "'";
      Filter filters = jqgrid.getFilters();
      if (filters != null && CollectionUtils.isNotEmpty(filters.getRules())) {
        for (SearchRule sr : filters.getRules()) {
          String field = sr.getField();
          Object data = sr.getData();
          boolean isDate = false;
          Field f = ReflectUtil.getField(sr.getField(), BusinessModelDto.class);
          if (f != null) {
            if (f.getType().equals(Date.class)) {
              data = "to_date('" + data + "','yyyy-MM-dd')";
              isDate = true;
            }
          }
          if (sr.getOp() == SearchRuleOption.eq) {
            whereCase = whereCase + " and " + field + " ='" + data + "' ";
          } else if (sr.getOp() == SearchRuleOption.nc) {
            whereCase = whereCase + " and " + field + " not in ('" + data + "') ";
          } else if (sr.getOp().equals(SearchRuleOption.gt)) {
            whereCase = whereCase + " and " + field + (isDate ? " > " + data : " > '" + data + "'");
          } else if (sr.getOp().equals(SearchRuleOption.lt)) {
            whereCase = whereCase + " and " + field + (isDate ? " < " + data : " < '" + data + "'");
          } else if (sr.getOp().equals(SearchRuleOption.ge)) {
            whereCase =
                    whereCase + " and " + field + (isDate ? " >= " + data : " >= '" + data + "'");
          } else if (sr.getOp().equals(SearchRuleOption.le)) {
            whereCase =
                    whereCase + " and " + field + (isDate ? " <= " + data : " <= '" + data + "'");
          } else {
            whereCase = whereCase + " and " + field + " like '%" + data + "%' ";
          }
        }
      }
      /*
       * String countCase =
       * " select count( t_biz_base_business_model.business_id) from t_biz_base_business_model t_biz_base_business_model "
       * +
       * " join T_SYS_USER T_SYS_USER on T_SYS_USER.u_Id=t_biz_base_business_model.save_model_person where 1=1 and t_biz_base_business_model.type = '"
       * + type + "'" + whereCase;
       */
      String countCase = listCase + whereCase;
      listCase = listCase + whereCase + " order by t_biz_base_business_model.save_model_time desc ";

      // List<Object> countList = businessModelBiz.findObjectBySql(countCase, 0, 10, null);
      int count = businessModelBiz.findEntityCountBySql(countCase, null);
      List<Object> list = businessModelBiz.findObjectBySql(listCase,
              (jqgrid.getPage().getPageNumber() * jqgrid.getPage().getPageSize()) + 1,
              jqgrid.getPage().getPageSize(), null);
      if (list != null && list.size() > 0) {
        List<BusinessModelDto> businessModelDtos = new ArrayList<>();
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Object o : list) {
          Object[] os = (Object[]) o;
          BusinessModelDto dto = new BusinessModelDto();
          dto.setId(os[0].toString());
          if (os[1] == null) {
            dto.setModel_name("");
          } else {
            dto.setModel_name(os[1].toString());
          }
          dto.setSave_model_time(fmt.parse(os[2].toString()));
          dto.setSave_model_person(os[4].toString());
          dto.setType(os[5].toString());
          dto.setBusiness_id(os[6] == null ? "" : os[6].toString());
          if ("D".equals(type)) {
            if (os[7] == null) {
              dto.setIs_record_info("");
            } else {
              dto.setIs_record_info(os[7].toString());
            }
          } else {
            dto.setIs_record_info("");
          }
          businessModelDtos.add(dto);
        }
        /*
         * long count = 0; if (CollectionUtils.isNotEmpty(countList)) { count = ((BigDecimal)
         * countList.get(0)).longValue(); }
         */
        Page<BusinessModelDto> businessModelDtoPage =
                new PageImpl<>(businessModelDtos, jqgrid.getPage(), count);
        return businessModelDtoPage;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * ###页面上使用$.load加载模板#### 在下单页面选择模板
   *
   * @param bizId 模板ID
   * @param bizType 模板类型<br/>
   *        \t all：拖车、货代、报关, C：拖车, D：货代, F：报关
   * @return 下单页面
   */
  @RequestMapping("/order_custom_page_pick_model")
  public String orderCustomPagePickModel(Model model, String bizId, String bizType,
                                         String isTongguanYth, String type, String dType,String isAgent) {
    // bizType = "F"; //这里只需要报关类型的模板
    Declaration declaration = declarationModelBiz.queryModelAndConvertToDeclaration(bizId, bizType);
    declarationModelBiz.findOneModel(bizId);
    Declaration.sortCommidities(declaration);
    chnToCodeFix.chnToCode(declaration);
    /**
     * 通过代录人客户公司id查询公司名
     */
   /* String agentName=null;
    if (!"".equals(declaration.getAgent_for_com_id())&&declaration.getAgent_for_com_id()!=null) {
       agentName = cusInfoService.selectAgentNameById(declaration.getAgent_for_com_id());
    }*/
    declaration.setBusinessId(null);
    declaration.setContract_date(new Date());
    declaration.setReport_date(new Date());
    declaration.setDeclaContainers(null);
   /* if (!"".equals(agentName)){
      declaration.setAgent_name(agentName);
    }*/
    FreeMarkerUtils.prepareUseForFTL(declaration);
    declaration.clearActionChain();
    declaration.setActionChain(Declaration.ChainModel.userModel, true);
    model.addAttribute("declaration", declaration);
    if (StringUtils.isNotEmpty(dType)) {
      declaration.setDeclaration_type(dType);;
      model.addAttribute("type", dType);
    }

    if (StringUtils.isNotEmpty(type)) {
      declaration.setTradeType(type);
    }
    model.addAttribute(OrderAction.OPSTATE_STRING, "insert");
    model.addAttribute("isCCI", isTongguanYth);
    model.addAttribute("isAgent",isAgent);
    String portCode = declaration.getSupCompany().getPort_code();
    if (StringUtils.isNotEmpty(portCode)) {
      boolean hasSO = declarationPortBiz.findHasSOByPortCode(portCode);
      model.addAttribute("soState", hasSO);
    }
    boolean isSupplier = false;
    try {
      isSupplier = "CC".equals(LoginUtil.getLoginUser().getCompany().getType());
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    model.addAttribute("isSupplier", isSupplier + "");
    if ("CROPPED5".equals(declaration.getEnter_page())){
      return SIMPLE_ORDER_DECLARE_PAGE;
    }else{
      return OrderAction.ORDER_DECLARE_PAGE;
    }

  }

  /**
   * excel导入功能
   *
   * @author han
   * @param file 文件流
   * @param isTongguanYth 是否通关一体化，页面传递过来的参数
   * @param tradeType 交易类型，页面传递过来的参数
   * @param model
   * @return
   */
  @RequestMapping("/importExcel")
  public String importExcel(@RequestParam("excelImportFile") MultipartFile file,
                            String isTongguanYth, String tradeType, Model model) {
    Declaration declaration = null;
    try {
      MsgExcel excelMsg = ExcelImportUtils.excelToBean(file.getInputStream());
      List<String> message = (ArrayList<String>) excelMsg.get("message");
      declaration = (Declaration) excelMsg.get("declaration");
      if (message != null && message.size() > 0) {
        model.addAttribute("errorMsg", message.toString() + "导入的时候存在错误,请在平台从重新输入或重新导入。");
      }
      List<JSONObject> companyList = tGenSupSrvProvideService.selCompanyGkBgx(null);
      Map<String, String> knMap = new HashMap<String, String>();// 口岸Map
      Map<String, String> bgxMap = new HashMap<String, String>();// 报关行Map
      declaration.setIsTongguanYth(isTongguanYth);
      // 翻译进，出口口岸和报关行
      if (companyList != null && companyList.size() > 0) {
        for (JSONObject jsonObject : companyList) {
          bgxMap.put(jsonObject.getString("name"), jsonObject.getString("id"));
          knMap.put(jsonObject.getString("port"), jsonObject.getString("port_code"));
        }
      }
      if (declaration != null) {
        if (StringUtils.isNotEmpty(declaration.getExport_port())
                && knMap.containsKey(declaration.getExport_port())) {
          declaration.setExport_port_code(knMap.get(declaration.getExport_port()));
        }

        if (StringUtils.isNotEmpty(declaration.getDeclaration_port())
                && knMap.containsKey(declaration.getDeclaration_port())) {
          declaration.setDeclaration_port_code(knMap.get(declaration.getDeclaration_port()));
        }

        if (declaration.getSupCompany() != null
                && knMap.containsKey(declaration.getSupCompany().getName())) {
          declaration.getSupCompany().setId(knMap.get(declaration.getSupCompany().getName()));
        }
      }

      Declaration.sortCommidities(declaration);
      chnToCodeFix.chnToCode(declaration);
      declaration.setBusinessId(null);
      FreeMarkerUtils.prepareUseForFTL(declaration);
      declaration.clearActionChain();
      declaration.setActionChain(Declaration.ChainModel.userExcl, true);
      declaration.setTradeType(tradeType);
      model.addAttribute("declaration", declaration);
      model.addAttribute("type", Declaration.DECLARATION_TYPE_EXPORT);
      model.addAttribute(OrderAction.OPSTATE_STRING, "insert");
      model.addAttribute("soState", false);
    } catch (Exception e) {
      declaration = new Declaration();
      Declaration.sortCommidities(declaration);
      chnToCodeFix.chnToCode(declaration);
      declaration.setBusinessId(null);
      FreeMarkerUtils.prepareUseForFTL(declaration);
      declaration.clearActionChain();
      declaration.setActionChain(Declaration.ChainModel.userExcl, true);
      declaration.setTradeType(tradeType);
      model.addAttribute("declaration", declaration);
      model.addAttribute("type", Declaration.DECLARATION_TYPE_EXPORT);
      model.addAttribute(OrderAction.OPSTATE_STRING, "insert");
      model.addAttribute("soState", false);
      model.addAttribute("errorMsg", e.getMessage());
    }
    return OrderAction.ORDER_DECLARE_PAGE;
  }

  /**
   * 准备保存为模板
   */
  @RequestMapping("/prepareSveAsModel")
  public String prepareSaveAsModel(String businessId, String isRecordInfo,String isAgent, Model model) {
    model.addAttribute("businessId", businessId);
    model.addAttribute("isRecordInfo", isRecordInfo);
    model.addAttribute("isAgent",isAgent);
    return PathEnum.saveAsModel.toPath();
  }

  /**
   * 将报关单转换为报关单模板并进行保存
   *
   * @param declaration 报关单
   * @param modelName 模板名称
   * @param modelType 模板类型
   */
  @RequestMapping("/saveAsModel")
  @ResponseBody
  public String saveAsModel(Declaration declaration, String modelName, String modelType,
                            String isRecordInfo, String businessId, String isTongguanYth,String isAgent) {
    String format = "{\"rs\":\"%s\", \"code\":\"%s\"}";
    declaration.setIs_record_info(isRecordInfo);
    declaration.setBusinessId(businessId);
    /**
     * 判断是否为代录单公司
     */
    String comId=LoginUtil.getLoginUser().getCompany().getId();
    String comType=cusInfoService.selectComTypeById(comId);
    if (!"0".equals(comType)){
      declaration.setEnter_type("1");
    }else {
      declaration.setEnter_type("0");
    }
    try {
      GtimpBusinessUtil.checkDeclaration(declaration);
      declarationModelBiz.saveAsModel(declaration, modelName, modelType, isTongguanYth,isAgent);
    } catch (SaveException e) {
      // S_400 保存异常
      return String.format(format, "0", "S_400");
    } catch (MRDValidationException me) {
      return String.format(format, "-1", me.getMessage());
    }

    return String.format(format, "1", "S_200");
  }

  /**
   * 将报关单转换为报关单模板并进行保存
   *
   * @param modelName 模板名称
   */
  @RequestMapping("/saveAsModel2.0")
  @ResponseBody
  public String saveAsModelV20(String id, String modelName) {
    String format = "{\"rs\":\"%s\", \"code\":\"%s\"}";
    try {
      declarationModelBiz.saveAsModelV20(id, modelName);
    } catch (Exception e) {
      // S_400 保存异常
      e.printStackTrace();
      return String.format(format, "0", "S_400");
    }
    return String.format(format, "1", "S_200");
  }

  /**
   * 模板名称验证
   *
   * @param modelName 模板名称
   * @param id 模板ID
   * @return 模板名称是否可用。 1：可用 0：不可用
   */
  @RequestMapping("/modelNameValidator")
  public String modelNameValidator(String modelName, String id) {
    String format = "{rs:%s}";
    return String.format(format, declarationModelBiz.validModelName(modelName, id) ? "1" : "0");
  }

  public BusinessModelBiz getBusinessModelBiz() {
    return businessModelBiz;
  }

  public void setBusinessModelBiz(BusinessModelBiz businessModelBiz) {
    this.businessModelBiz = businessModelBiz;
  }

  public DeclarationBiz getDeclarationBiz() {
    return declarationBiz;
  }

  public void setDeclarationBiz(DeclarationBiz declarationBiz) {
    this.declarationBiz = declarationBiz;
  }

  public TrailBiz getTrailBiz() {
    return trailBiz;
  }

  public void setTrailBiz(TrailBiz trailBiz) {
    this.trailBiz = trailBiz;
  }

}
